package com.simple.framework.core.rsa.aop;


import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.simple.framework.aspect.Encrypt;
import com.simple.framework.core.domain.R;
import com.simple.framework.core.rsa.utils.AES;
import com.simple.framework.core.wrapper.RequestWrapper;
import com.simple.framework.utils.ServletUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * @Description 传输加密模块AOP，对接口的出参进行加密,注意顺序不能乱，此AOP必须第一个执行
 * @Author xiaoke
 * @Date 2024/8/18 16:28
 * @Version 1.0
 */
@Order(value = 0)
@Aspect
@Component
public class EncryptAOP {
    @Pointcut("@annotation(com.simple.framework.aspect.Encrypt)")
    public void point () {}

    /**
     *  环绕增强，加密出参
     * */
    @Around(value = "point() && @annotation(encrypt)")
    public Object around (ProceedingJoinPoint joinPoint , Encrypt encrypt) throws Throwable {
        //返回的结果
        Object returnValue = null;
        //从当前上下文提取request
        HttpServletRequest request = ServletUtil.getRequest();
        //请求体中的json参数
        String body = "";

        //把可能出错的逻辑，放到try-catch
        try {
            body = new RequestWrapper(request).getBodyString();
        }catch (Exception e) {

        }finally {
            //不管怎样，保证业务必须执行
            returnValue = joinPoint.proceed();
        }

        //把接口的出参，用前端此次传过来的AES密钥进行加密，然后返回
        JSONObject jsonObject = JSON.parseObject(body);
        String encryptData = AES.encryptToBase64(JSON.toJSONString(returnValue), jsonObject.getString("aesKey"));

        return R.success(encryptData);
    }
}
